package com.wanmei.util;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class ImageUtil {

    //
    public static final String  REAL_PATH ="C:\\Users\\LiYang\\Desktop\\TestUploadImages\\";

    // JGP格式
    public static final String JPG = "jpg";
    // GIF格式
    public static final String GIF = "gif";
    // PNG格式
    public static final String PNG = "png";
    // BMP格式
    public static final String BMP = "bmp";
    /**
     * 转换图片格式
     *
     * @param oldImage   原来上传的文件
     * @param formatName 要转成的格式
     * @param newImage   新的图片
     * @throws IOException
     */
    public static void changeImage(File oldImage, String formatName, File newImage) throws IOException {
        BufferedImage bufferedImage;
//            1. 读取图片
        bufferedImage = ImageIO.read(oldImage);
        //2.创建一个空白大小相同的RGB背景
        BufferedImage newBufferedImage = new BufferedImage(bufferedImage.getWidth(), bufferedImage.getHeight(), BufferedImage.TYPE_INT_RGB);
        newBufferedImage.createGraphics().drawImage(bufferedImage, 0, 0, Color.WHITE, null);
//            3.再次写入的时候以jpeg图片格式
        ImageIO.write(newBufferedImage, formatName, newImage);
        System.out.println("成功将png格式图片转换为jpg格式");
    }


    //时间戳+随机数”来命名文件
    public static String getImageNewName() {
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String now = simpleDateFormat.format(date);
        int random = (int) (Math.random() * 10000);
        return now + random;

    }


}
